package com.ruyuan.little.project.spring.handler;

import com.ruyuan.little.project.common.dto.CommonResponse;
import com.ruyuan.little.project.spring.enums.EducationBusinessErrorCodeEnum;
import com.ruyuan.little.project.spring.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author little
 */
@ControllerAdvice
@ResponseBody
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    /**
     * 日志组件
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public CommonResponse handleException(Exception e) {
        LOGGER.error("系统异常错误信息:{}", e);
        return CommonResponse.fail();
    }

    @ExceptionHandler(value = BusinessException.class)
    public CommonResponse handleBusinessException(BusinessException e) {
        LOGGER.error("系统异常错误信息:{}", e);
        return CommonResponse.fail();
    }

    /**
     * 统一处理请求参数校验(实体对象传参-form)
     *
     * @param e BindException
     * @return CommonResponse
     */
    @ExceptionHandler(BindException.class)
    public CommonResponse validExceptionHandler(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        LOGGER.info("参数校验失败:{}", message);
        CommonResponse<String> commonResponse = new CommonResponse<>();
        commonResponse.setCode(EducationBusinessErrorCodeEnum.PARAMETER_VALIDATED_FAILED.getCode());
        commonResponse.setMessage(EducationBusinessErrorCodeEnum.PARAMETER_VALIDATED_FAILED.getMsg());
        commonResponse.setData(message.toString());
        return commonResponse;
    }


    /**
     * 统一处理请求参数校验(json)
     *
     * @param e ConstraintViolationException
     * @return CommonResponse
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        LOGGER.error(message.toString(), e);
        CommonResponse<String> commonResponse = new CommonResponse<>();
        commonResponse.setCode(EducationBusinessErrorCodeEnum.PARAMETER_VALIDATED_FAILED.getCode());
        commonResponse.setMessage(EducationBusinessErrorCodeEnum.PARAMETER_VALIDATED_FAILED.getMsg());
        commonResponse.setData(message.toString());
        return commonResponse;
    }
}
